package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.AdUserMapper;
import com.zhentao.model.admin.dto.LoginDto;
import com.zhentao.model.admin.pojo.AdUser;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.AdUserService;

import com.zhentao.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
* @author 许文倩
* @description 针对表【ad_user】的数据库操作Service实现
* @createDate 2024-07-01 11:34:33
*/
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
    implements AdUserService{
    @Resource
    AdUserMapper userMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if (StringUtils.isBlank(dto.getUsername()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"账号或密码为空");
        }
        //2.根据账号查询用户是否存在
        QueryWrapper<AdUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(AdUser::getUsername,dto.getUsername());
        AdUser adUser = userMapper.selectOne(queryWrapper);
        if (adUser ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"账号不存在");
        }

        ///3.校验密码
        String salt = adUser.getSalt();
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));

        if (pwd.equals(adUser.getPassword())){
            //登录成功 返回token
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            Map<String,Object> map=new HashMap<>();
            map.put("token",token);
            adUser.setPassword(null);
            adUser.setSalt(null);
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
    }
}




